package com.sdkj.fixed.asset.assets.service;

import cn.hutool.core.convert.Convert;
import com.sdkj.fixed.asset.api.assets.in_vo.PrintLabelParam;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseResult;
import com.sdkj.fixed.asset.common.exception.LogicException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @ClassName PrintLabelService
 * @Description TODO
 * @Author 张欣
 * @Date 2020/8/3 17:25
 */
@Service
public class PrintLabelService {
    @Autowired
    private WarehouseService warehouseService;
    private static Logger log = LoggerFactory.getLogger(WarehouseService.class);

    /**
     * 打印标签
     * @return
     */
    public void printLabel(PrintLabelParam param) throws InterruptedException, UnsupportedEncodingException {
        List<WarehouseResult> warehouseResults = warehouseService.queryByAssetIds(param.getAssatIds());
        if(warehouseResults.size() == 0){
            throw new LogicException("资产不存在");
        }
        //设置编码
        System.setProperty("jna.encoding", "GBK");
        //连接打印机
        int printConnect = printApiJni.printApi.PTK_Connect_Timer(param.getIp(), Integer.parseInt(param.getPort()), 5);
        if(printConnect != 0){
            throw new LogicException("请检查打印机ip、端口号是否正确，是否开机且连接网络");
        }
        try {
            for (WarehouseResult asset : warehouseResults){
                //清楚打印机缓冲
                printApiJni.printApi.PTK_ClearBuffer();
                //设置坐标原点
                printApiJni.printApi.PTK_SetCoordinateOrigin((60+35)*12,72);
                //从右下脚
                printApiJni.printApi.PTK_SetDirection('B');
                //标签高度
                printApiJni.printApi.PTK_SetLabelHeight(20*12,6*12,0,false);
                //标签宽度
                printApiJni.printApi.PTK_SetLabelWidth(70*12);
                //printApiJni.printApi.PTK_DrawLineXor(1,1,500,2);
                //资产名称
                int assetName = printApiJni.printApi.PTK_DrawText_TrueType(12, 35, 30, 0, "宋体", 1, 400, false, false, false, "资产名称:"+asset.getAssetName());
                if(assetName != 0){
                    getErrMessage(assetName,"设置条形码失败【"+asset.getAssetName()+"】");
                    throw new LogicException("设置打印资产名称参数失败");
                }
                int company = printApiJni.printApi.PTK_DrawText_TrueType(12, 70, 30, 0, "宋体", 1, 400, false, false, false, "购入公司:"+asset.getCompanyName());
                if(company != 0){
                    getErrMessage(company,"设置条形码失败【"+asset.getCompanyName()+"】");
                    throw new LogicException("设置购入公司参数失败");
                }
                int Barcode = printApiJni.printApi.PTK_DrawBarcode(10, 145, 0, "1", 3, 5, 90, 'N', asset.getAssetCode());
                if(Barcode != 0){
                    getErrMessage(Barcode,"设置条形码失败【"+asset.getAssetCode()+"】");
                    throw new LogicException("设置条形码失败");
                }
                //  设置frid内容
                int rfid = printApiJni.printApi.PTK_RWRFIDLabel(1, 1, 0, asset.getAssetCode().length(), 1, asset.getAssetCode());
                if(rfid != 0){
                    getErrMessage(rfid,"设置RFID信息失败");
                    throw new LogicException("设置RFID信息失败");
                }
                /*int result = printApiJni.printApi.PTK_PrintLabel(1, 1);
                if(result > 0){
                    getErrMessage(result,"打印标签失败【"+asset.getAssetCode()+"】");
                    throw new LogicException("打印标签失败");
                }*/
                //打印并返回RFID写入的内容
                byte[] pintResult_Byte = new byte[1024];
                int pintResult = printApiJni.printApi.PTK_RFIDEndPrintLabel(1, pintResult_Byte, 1024);
                System.out.println("RFID内容："+new String(pintResult_Byte));
                if(pintResult != 0){
                    getErrMessage(pintResult,"打印标签失败【"+asset.getAssetCode()+"】");
                    String pintResult_Str = new String(pintResult_Byte);
                    String err_message = "";
                    switch (pintResult_Str){
                        case "ERROR+EPC0003": err_message = "读不到TID";
                                          break;
                        case "ERROR+EPC0004": err_message = "读到写入失败";
                            break;
                        case "ERROR+EPC0005": err_message = "读到重复TID";
                            break;
                        case "ERROR+EPC0006": err_message = "重新盘点到多张新标签";
                            break;
                        default:err_message="未知错误";
                    }
                    if(pintResult_Str.contains("ERROR+EPC")){
                        log.error("写入RFID失败:"+pintResult_Str+"-"+err_message);
                        throw new LogicException("写入RFID失败:"+err_message+",请检查打印机，进行测纸");
                    }
                }


                Thread.sleep(2000);
            }
        } finally {
            int closeConnect = printApiJni.printApi.PTK_CloseConnect();
            if(closeConnect != 0){
                getErrMessage(closeConnect,"关闭连接失败");
                throw new LogicException("关闭连接失败");
            }
        }


    }
    private static String  getErrMessage(int code, String function) throws UnsupportedEncodingException {
        System.setProperty("jna.encoding", "GBK");
        byte[] errInfo_Byte = new byte[1024];
        printApiJni.printApi.PTK_GetErrorInfo(code, errInfo_Byte, errInfo_Byte.length);
        String errMessage = new String(errInfo_Byte, "GBK");
        log.error(function+":"+ errMessage);
        return errMessage;


    }
    private static void printTest() throws UnsupportedEncodingException {

    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        /*String aa = "sdsds";
         StringToHex16String(aa);*/
        printTest();

    }
    public static String StringToHex16String(String _str) throws UnsupportedEncodingException {
        //将字符串转换成字节数组。
        byte[] buffer = _str.getBytes("UTF-16");
        //定义一个string类型的变量，用于存储转换后的值。
        String  result = Convert.toHex(buffer);

            //将每一个字节数组转换成16进制的字符串，以空格相隔开。
        System.out.println(result);

        return result;
    }
}
